package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmUserDto;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.AppJwtUtil;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @作者 itcast
 * @创建日期 2021/4/12 10:19
 **/
@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements WmUserService {
    @Override
    public ResponseResult login(WmUserDto dto) {
        // 1参数
        if(dto == null || StringUtils.isBlank(dto.getName()) || StringUtils.isBlank(dto.getPassword())){
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 2根据用户名查询用户
        WmUser wmUser = getOne(Wrappers.<WmUser>lambdaQuery().eq(WmUser::getName, dto.getName()));
        if(wmUser==null){
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST,"用户不存在");
        }
        // 3. 判断密码是否正确
        String password = wmUser.getPassword();
        String inputPwd = DigestUtils.md5DigestAsHex((dto.getPassword() + wmUser.getSalt()).getBytes());
        if(!password.equals(inputPwd)){
            throw new CustomException(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        String token = AppJwtUtil.getToken(Long.valueOf(wmUser.getId()));
        // user    token
        Map map = new HashMap();
        map.put("token",token);
        wmUser.setPassword("");
        wmUser.setSalt("");
        map.put("user",wmUser);
        return ResponseResult.okResult(map);
    }
}
